/**************************************这里主要定义项目中一些公关函数的方法***************************************************** */

import Cookies from 'js-cookie';
import CryptoJS from 'crypto-js';

export const initDict = vm => {};

// 处理table显示过长，鼠标放上显示褐色对话框
export const setDialogBox = (h, params, val, len = 15) => {
    let texts = '';
    if (val.length > len) {
        texts = val.substring(0, len) + '...';
    } else {
        return h('div', val);
    }
    return h('div', [
        h(
            'Tooltip',
            {
                props: {
                    placement: 'bottom',
                    transfer: true
                },
                style: {
                    cursor: 'pointer'
                }
            },
            [
                //这个中括号表示是Tooltip标签的子标签
                texts, //表格列显示文字
                h(
                    'div',
                    {
                        slot: 'content',
                        style: {
                            whiteSpace: 'normal',
                            wordBreak: 'break-all',
                            wordWrap: 'break-word'
                        }
                    },
                    val
                ) //整个的信息即气泡内文字
            ]
        )
    ]);
};

//浮点数的精度解
export const toFixed = (num1, num2, type) => {
    if (num1 == undefined || num2 == undefined) {
        return null;
    }
    var num1_length =
        num1.toString().indexOf('.') > -1 && num1.toString().split('.')[1].length > 1
            ? num1.toString().split('.')[1].length
            : num1.toString().indexOf('-') > -1
            ? parseInt(num1.toString().split('-')[1])
            : 2;
    var num2_length =
        num2.toString().indexOf('.') > -1 && num2.toString().split('.')[1].length > 1
            ? num2.toString().split('.')[1].length
            : num2.toString().indexOf('-') > -1
            ? parseInt(num2.toString().split('-')[1])
            : 2;
    var minnum = Math.max(num1_length, num2_length);
    if (type == '*') {
        minnum = num1_length + num2_length;
    }
    if (type == '/') {
        minnum = 8;
    }
    var fixedNum = minnum;
    var beishu = Math.pow(10, fixedNum);
    var retNum = 0;
    switch (type) {
        case '+':
            if (num2 == 0) {
                return num1;
            }
            retNum = Math.round((num1 + num2) * beishu) / beishu;
            break;
        case '-':
            if (num2 == 0) {
                return num1;
            }
            retNum = Math.round((num1 - num2) * beishu) / beishu;
            break;
        case '*':
            retNum = Math.round(num1 * num2 * beishu) / beishu;
            break;
        case '/':
            retNum = Math.round((num1 / num2) * beishu) / beishu;
            break;
    }
    return retNum;
};

/**
 * 数字限制小数位和总长度
 * @param
 *  val: 数字
 *  num: 小数位个数
 *  len: 总长度
 */
export const limitDecimals = (val, num, len) => {
    let tempVal = val;
    val = val.replace(/[^\d.]/g, ''); //清除“数字”和“.”以外的字符
    val = val.replace(/^\./g, ''); //验证第一个字符是数字而不是.
    val = val.replace(/\.{2,}/g, '.'); //只保留第一个. 清除多余的.
    val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
    if (val.split('.').length > 1) {
        if (num == 0) {
            val = val.split('.')[0];
        } else {
            val = val.split('.')[0] + '.' + val.split('.')[1].substr(0, num);
        }
    }
    if (tempVal.startsWith('-')) val = '-' + val;
    if (len && val.length > len) val = val.substr(0, len);
    return val;
};

export const parseDate = date => {
    if (!date) {
        return '';
    } else {
        date = new Date(date);
    }
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    if (month < 10) {
        month = '0' + month;
    }
    if (day < 10) {
        day = '0' + day;
    }
    if (hours < 10) {
        hours = '0' + hours;
    }
    if (minutes < 10) {
        minutes = '0' + minutes;
    }
    if (seconds < 10) {
        seconds = '0' + seconds;
    }
    //const t = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    const t = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;
    return t;
};

export const parseDateToMin = date => {
    if (!date) {
        return '';
    } else {
        date = new Date(date);
    }
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    if (month < 10) {
        month = '0' + month;
    }
    if (day < 10) {
        day = '0' + day;
    }
    if (hours < 10) {
        hours = '0' + hours;
    }
    if (minutes < 10) {
        minutes = '0' + minutes;
    }
    if (seconds < 10) {
        seconds = '0' + seconds;
    }
    const t = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;

    return t;
};

export const parseDateToSec = date => {
    if (!date) {
        return '';
    } else {
        date = new Date(date);
    }
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    if (month < 10) {
        month = '0' + month;
    }
    if (day < 10) {
        day = '0' + day;
    }
    if (hours < 10) {
        hours = '0' + hours;
    }
    if (minutes < 10) {
        minutes = '0' + minutes;
    }
    if (seconds < 10) {
        seconds = '0' + seconds;
    }
    const t = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    return t;
};

// 设置浏览器显示的title名称
export const setTitle = title => {
    window.document.title = title || 'admin';
};

// 设置token
export const setToken = (token, tokenName = 'CommData') => {
    Cookies.set(tokenName, token);
};
// 获取token
export const getToken = (tokenName = 'CommData') => {
    return Cookies.get(tokenName);
};
// 清除cookies
export const removeToken = (tokenName = 'CommData') => {
    Cookies.remove(tokenName);
};

// sessionStorage存储页面所需的一些信息
export const setSessionStorage = (keyName, Info) => {
    // 加密处理
    let encryptInfo = Encrypt(Info);
    sessionStorage.setItem(keyName, encryptInfo);
};
// 获取sessionStorage存储的信息
export const getSessionStorage = keyName => {
    let Info = sessionStorage.getItem(keyName);
    // 解密处理
    let decryptInfo = Decrypt(Info);
    return decryptInfo;
};
// 清除sessionStorage
export const clearSessionStorage = (...agm) => {
    // 判断有没有传入要删除的  如果有  则按传入的key删除  如果没有  则默认全部删除
    if (agm.length > 0) {
        for (let i = 0; i < agm.length; i++) {
            sessionStorage.removeItem(agm[i]);
        }
    } else {
        sessionStorage.clear();
    }
};

// 从页面的URL中获取参数的方法
export const getParams = url => {
    const keyValueArr = url.split('?')[1].split('&');
    let paramObj = {};
    keyValueArr.forEach(item => {
        const keyValue = item.split('=');
        paramObj[keyValue[0]] = keyValue[1];
    });
    return paramObj;
};

// 使用cryptojs来处理页面存储信息的加密以及解密
const key = CryptoJS.enc.Utf8.parse('1234123412ABCDEF'); //十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412'); //十六位十六进制数作为密钥偏移量
//加密方法
const Encrypt = word => {
    let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString().toUpperCase();
};
//解密方法
const Decrypt = word => {
    if (word != null) {
        let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
        let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
        let decrypt = CryptoJS.AES.decrypt(srcs, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        return decryptedStr.toString();
    }
};
